package com.woniu.common.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author ltyipx
 * @version 1.0
 * @description:TODO
 * @date 2024/7/30 11:18
 */
public class RabbitSendMessage {
    public static  <T> void send(StringRedisTemplate redisTemplate,RabbitTemplate rabbitTemplate, String exchange, String routingKey, T msg) {
        send(redisTemplate,rabbitTemplate,exchange,routingKey,msg,null);
    }

    public static  <T> void send(StringRedisTemplate redisTemplate,RabbitTemplate rabbitTemplate, String exchange, String routingKey, T msg,String appId) {
        CorrelationData correlationData = new CorrelationData();
        Message message = new Message(JSON.toJSONBytes(msg));
        correlationData.setReturnedMessage(message);
        correlationData.getReturnedMessage().getMessageProperties().setReceivedExchange(exchange);
        correlationData.getReturnedMessage().getMessageProperties().setReceivedRoutingKey(routingKey);
        //消息中的
        correlationData.getReturnedMessage().getMessageProperties().setAppId(appId);

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //1、生成token，并保存到redis中
                String token = IdUtil.fastUUID();
                redisTemplate.opsForValue().set(token,token,20, TimeUnit.MINUTES);
                //2、发送消息时，带token
                message.getMessageProperties().setMessageId(token);
                message.getMessageProperties().setAppId(appId);
                return message;
            }
        };
        rabbitTemplate.convertAndSend(exchange,routingKey, msg,messagePostProcessor,correlationData);
    }
}
